package game.unitmanager.commands 
{
	import core.Command;
	import game.map.Map;
	import game.mapviewer.ArmyIcon;
	import game.mapviewer.MapViewer;
	import game.unitmanager.ArmyController;
	import game.unitmanager.UnitsManager;
	/**
	 * ...
	 * @author rnk
	 */
	public class MoveCommand extends Command
	{
		private var army:ArmyController;
		private var destinationProvinceUid:String;
		private var mapModel:Map;
		private var mapView:MapViewer;
		private var unitManager:UnitsManager;
		
		private var killArmyOnDestinationReach:Boolean = false;
		
		public function MoveCommand(army:ArmyController, destinationProvinceUid:String) 
		{
			this.army = army;
			this.destinationProvinceUid = destinationProvinceUid;
			unitManager = army.papa;
			mapModel = unitManager.papa.mapModel;
			mapView = unitManager.papa.mapView;
		}
		
		override public function Execute():void
		{
			if (destinationProvinceUid == army.model.province.uid)
			{
				Callback();
				return;
			}
			
			var otherArmy:ArmyController = unitManager.GetArmy(destinationProvinceUid);
			
			if (otherArmy)
			{
				killArmyOnDestinationReach = true;
				
			} else
			{
				
			}
			
			army.view.MoveArmy(destinationProvinceUid, OnArmyViewFinishedMoving);
		}
		
		private function OnArmyViewFinishedMoving():void 
		{
			mapModel.GetProvince(destinationProvinceUid).AddArmy(army.model);
			
			if (killArmyOnDestinationReach)
			{
				//kill model(assuming its already been cleared and removed from province model)
				army.model = null;				
				//kill view				
				mapView.RemoveArmy(army.view);
				army.view = null;
				//kill controller
				unitManager.RemoveArmy(army);
				//refresh other army view
				var otherArmy:ArmyController = unitManager.GetArmy(destinationProvinceUid);
				otherArmy.view.Refresh();
				
			} else
			{
				
			}
			
			Callback();
		}
		
	}

}